package com.lagou.common.handler;

import com.lagou.common.domain.ServiceData;
import com.lagou.common.rpc.RpcData;
import com.lagou.common.rpc.RpcRoute;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class ServerHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        // 判断是否符合约定，符合则调用本地方法，返回数据
        // msg:  UserService#sayHello#are you ok?
        RpcData  rpcRequest = (RpcData) msg;
        String methodName = rpcRequest.getMethodName();
        ServiceData serviceData = RpcRoute.getInstance().handlerMap.get(methodName);
        String result = (String)serviceData.getMethod().invoke(serviceData.getaClass().newInstance(),rpcRequest.getArgs());
        RpcData rpcData = new RpcData();
        rpcData.setValue(result);
        ctx.writeAndFlush(rpcData);
    }

}
